﻿using QD.SQLHelper;
using QD.Tools;
using QD_Clients.Code;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace QD_Clients.Tester
{
    public partial class Test_QDDevPlat : BaseForm
    {
        private int PageSize = 500;
        private int TotalPage = 1;
        private PageState PageState = PageState.Browse;
        private string _QfCode = null;
        private string _LeaderCode = null;
        private string _Status = null;
        private string _DeveloperCode = null;

        /// <summary>
        /// BUG编号
        /// </summary>
        private string _TSID
        {
            get
            {
                return this.latsid.Text.Trim();
            }
            set
            {
                this.latsid.Text = value;
            }
        }
        public Test_QDDevPlat()
        {
            InitializeComponent();
            this.gridList.InitGrid();
        }

        private void Test_QDDevPlat_Load(object sender, EventArgs e)
        {
            BindMenu();
            if (QDUserHelper.CurUser.IsManager)
            {
                toolStripButton1.Visible = true;
            }
            this.navigator.BindingSource = this.bindingSource;
            this.bugList.DataSource = this.bindingSource;
            this.KeyPreview = true;
            this.KeyDown += BaseForm_KeyDown;

            this.bugList.InitGrid(false, false, true);
            //this.bugList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            this.richTxtTools1.RichText = this.BUGContext;

            QDResources db = new QDResources();
            DataTable dt_qduser = db.Query("select * from QDUser order by Uid asc");
            this.SubmitToCode.DisplayMember = "UName";
            this.SubmitToCode.ValueMember = "Uid";
            this.SubmitToCode.DataSource = dt_qduser;

            DataTable dt_transfer = dt_qduser.Copy();
            this.TransferMan.DisplayMember = "UName";
            this.TransferMan.ValueMember = "Uid";
            this.TransferMan.DataSource = dt_transfer;
            this.TransferMan.SelectedIndex = -1;

            DataTable dt_qdDataBase = db.Query("select * from QDDataBase");
            this.cmbQfCode.DisplayMember = "QfName";
            this.cmbQfCode.ValueMember = "QfCode";
            this.cmbQfCode.DataSource = dt_qdDataBase;
            this.cmbQfCode.SelectedIndex = -1;
            //ts_append_Click(sender, e);
            //DataBind();
            gridList_CellContentDoubleClick(null, new DataGridViewCellEventArgs(0, 0));
        }
        /// <summary>
        /// 绑定左侧产品菜单
        /// </summary>
        private void BindMenu()
        {
            QDResources db = new QDResources();
            DataTable dt = db.Query("select QfCode,QfName,TesterCode,DeveloperCode,LeaderCode from QDDataBase");
            this.gridList.DataSource = dt;
        }

        /// <summary>
        /// 是否编辑
        /// </summary>
        private void BeginEdit(bool isEdit)
        {
            this.BUGName.ReadOnly =
                this.BUGContext.ReadOnly = !isEdit;
        }

        private void ts_append_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_QfCode))
            {
                addClick();
                this.cmbQfCode.SelectedValue = _QfCode;
                this.SubmitToCode.SelectedValue = _DeveloperCode;
            }
            else
            {
                PromptHelper.Prompt("请选择产品后再操作！");
            }
        }
        private void addClick()
        {
            BeginEdit(true);

            this.SubmitToCode.SelectedIndex = -1;
            this.cmbQfCode.SelectedIndex = -1;
            this.BUGName.Clear();
            this.BUGContext.Clear();
            this.lacreatorname.Text = "";
            this.lacreatedate.Text = "";
            this.ProcessDesc.Text = "";
            PageState = PageState.Append;

            this.SubmitToCode.Enabled = true;
            //this.cmbQfCode.Enabled = true;

            this._TSID = "";
            this.listLog.Items.Clear();
        }

        private void ts_modify_Click(object sender, EventArgs e)
        {
            BeginEdit(true);
            PageState = PageState.Modify;
        }

        private void ts_Update_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState == PageState.Browse)
                {
                    throw new Exception("当前BUG未修改！");
                }
                string action = "";
                if (this.BUGName.Text.Trim().Length == 0)
                {
                    throw new Exception("标题不能为空！");
                }
                else if (this.cmbQfCode.SelectedIndex == -1)
                {
                    throw new Exception("请选择产品！");
                }
                else if (this.SubmitToCode.SelectedIndex == -1)
                {
                    throw new Exception("请选择提交给谁！");
                }

                QDResources db = new QDResources();
                var path = db.ExecuteScalar("select BTFilePath from Sys_Setting");
                if (path == null)
                {
                    throw new Exception("请设置存储路径！");
                }
                Test_BUG mst = null;
                if (!string.IsNullOrEmpty(this._TSID))
                {
                    mst = db.Test_BUG.FirstOrDefault(p => p.TSID == this._TSID);
                    if (mst == null)
                    {
                        throw new Exception("BUG[" + this._TSID + "]不存在或已经被删除！");
                    }
                    action = "修改";
                }
                else
                {
                    mst = new Test_BUG();
                    mst.TSID = Test_BUGHelper.GetNewId();
                    mst.QfCode = this.cmbQfCode.SelectedValue.ToString();
                    mst.CreatorCode = QDUserHelper.CurUser.Uid;
                    mst.CreatorName = QDUserHelper.CurUser.UName;
                    mst.CreateDate = DateTime.Now;
                    mst.SubmitToCode = this.SubmitToCode.SelectedValue.ToString();
                    mst.SubmitToName = this.SubmitToCode.Text;
                    mst.NextProcessorCode = this.SubmitToCode.SelectedValue.ToString();
                    mst.NextProcessorName = this.SubmitToCode.Text;
                    mst.Status = TestStatus.noSubmit.ToString();
                    db.Test_BUG.Add(mst);
                    action = "新增";
                }
                mst.BUGName = this.BUGName.Text.Trim();
                this._TSID = mst.TSID;
                byte[] b = RtfHelper.GetRichTextBoxData(this.BUGContext);
                mst.FilePath = RtfHelper.UploadFile(b, path.ToString());
                db.SaveChanges();
                BeginEdit(false);
                PromptHelper.Prompt("保存成功！");

                Test_BUGHelper.AddBugProcessList(db, mst.TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), action, "", "");
                db.SaveChanges();

                InitUIData(mst.TSID);
                DataBind();
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void ts_delete_Click(object sender, EventArgs e)
        {
            try
            {
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认删除当前BUG？") == DialogResult.OK)
                    {
                        if (mst.Status != TestStatus.noSubmit.ToString())
                        {
                            throw new Exception("当前BUG不处理于未提交状态，不能删除！");
                        }
                        else
                        {
                            dbConfig.Test_BUG.Remove(mst);

                            //删除日志
                            var query = dbConfig.Test_BUGProcessList.Where(p => p.TSID == mst.TSID);
                            foreach (var q in query)
                            {
                                dbConfig.Test_BUGProcessList.Remove(q);
                            }
                            dbConfig.SaveChanges();
                            PromptHelper.Prompt("删除成功！");
                            DataBind();
                            ts_append_Click(sender, e);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.curPageIndex.Text != "1")
            {
                this.curPageIndex.Text = "1";
            }
            else
            {
                DataBind();
            }
        }

        private void navigator_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private int GetCurPageIndex()
        {
            int pageIndex = 1;
            string txtCurPageIndex = this.curPageIndex.Text.Trim();
            if (string.IsNullOrEmpty(txtCurPageIndex))
            {
                throw new Exception("请输入正确的页码！");
            }
            else if (!int.TryParse(txtCurPageIndex, out pageIndex))
            {
                throw new Exception("请输入正确的页码！");
            }
            return pageIndex;
        }

        private void DataBind()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.curPageIndex.Text.Trim()))
                {
                    int pageIndex = GetCurPageIndex();
                    string filter = getFilter();
                    if (!string.IsNullOrEmpty(_QfCode))
                    {
                        QDResources db = new QDResources();
                        string sql1 = string.Format("select top 100  percent  ROW_NUMBER() over(order by TSID asc) as AID,* from Test_BUG where QfCode='{0}' and " + filter + " order by LastProcessDate desc", _QfCode);
                        string sql2 = "";
                        if (QDUserHelper.CurUser.IsManager)
                        {
                            sql2 = string.Format("select  top {0} TSID,'['+SubmitToName+'] '+BUGName as BUGName,CreateDate from ({1}) t where AID>{2} order by AID asc", PageSize, sql1, ((pageIndex - 1) * PageSize).ToString());
                        }
                        else
                        {
                            sql2 = string.Format("select  top {0} TSID,'['+SubmitToName+'] '+BUGName as BUGName,CreateDate from ({1}) t where AID>{2} order by AID asc", PageSize, sql1, ((pageIndex - 1) * PageSize).ToString());
                        }
                        DataTable dt = db.Query(sql2);
                        this.bindingSource.DataSource = dt;



                        object qtyNoSubmit = db.ExecuteScalar("select count(*) from Test_BUG where QfCode='" + _QfCode + "' and " + getFilter("tpNoSubmit"));
                        this.tpNoSubmit.Text = "未提交(" + qtyNoSubmit.ToString() + ")";

                        //object qtySubmit = db.ExecuteScalar("select count(*) from Test_BUG where  QfCode='" + _QfCode + "' and " + getFilter("tpSubmit"));
                        //this.tpSubmit.Text = "已提交(" + qtySubmit.ToString() + ")";

                        object qtywaitProcess = db.ExecuteScalar("select count(*) from Test_BUG where QfCode='" + _QfCode + "' and " + getFilter("tpWaitProcess"));
                        this.tpWaitProcess.Text = "待处理(" + qtywaitProcess.ToString() + ")";

                        //object qtyProcessed = db.ExecuteScalar("select count(*) from Test_BUG where QfCode='" + _QfCode + "' and " + getFilter("tpProcessed"));
                        //this.tpProcessed.Text = "已处理(" + qtyProcessed.ToString() + ")";

                        object qtyConfirm = db.ExecuteScalar("select count(*) from Test_BUG where QfCode='" + _QfCode + "' and " + getFilter("tpConfirm"));
                        this.tpConfirm.Text = "待确认(" + qtyConfirm.ToString() + ")";

                        object qtyFinish = db.ExecuteScalar("select count(*) from Test_BUG where  QfCode='" + _QfCode + "' and " + getFilter("tpFinish"));
                        this.tpFinish.Text = "已完成(" + qtyFinish.ToString() + ")";

                        object qtyRecall = db.ExecuteScalar("select count(*) from Test_BUG where  QfCode='" + _QfCode + "' and " + getFilter("tpRecall"));
                        this.tpRecall.Text = "已撤消(" + qtyRecall.ToString() + ")";

                        switch (this.tabControl1.SelectedTab.Name)
                        {
                            case "tpNoSubmit":
                                this.totalCount.Text = qtyNoSubmit.ToString();
                                TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyNoSubmit) * 1.0 / PageSize)));
                                break;
                            //case "tpSubmit":
                            //    this.totalCount.Text = qtySubmit.ToString();
                            //    TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtySubmit) * 1.0 / PageSize)));
                            //    break;
                            case "tpWaitProcess":
                                this.totalCount.Text = qtywaitProcess.ToString();
                                TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtywaitProcess) * 1.0 / PageSize)));
                                break;
                            //case "tpProcessed":
                            //    this.totalCount.Text = qtyProcessed.ToString();
                            //    TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyProcessed) * 1.0 / PageSize)));
                            //    break;
                            case "tpConfirm":
                                this.totalCount.Text = qtyConfirm.ToString();
                                TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyConfirm) * 1.0 / PageSize)));
                                break;
                            case "tpFinish":
                                this.totalCount.Text = qtyFinish.ToString();
                                TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyFinish) * 1.0 / PageSize)));
                                break;
                            case "tpRecall":
                                this.totalCount.Text = qtyRecall.ToString();
                                TotalPage = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToInt32(qtyRecall) * 1.0 / PageSize)));
                                break;
                        }
                    }
                    else
                    {
                        QD.Tools.PromptHelper.Prompt("请选择产品后再操作！");
                    }
                }
            }
            catch (Exception ex)
            {
                QD.Tools.PromptHelper.Prompt(ex);
            }
        }

        private string getFilter()
        {
            string filter = getFilter(this.tabControl1.SelectedTab.Name);

            string _keyTxt = this.txtKey.Text.Trim();
            if (!string.IsNullOrEmpty(_keyTxt))
            {
                if (!string.IsNullOrEmpty(filter))
                {
                    filter += " and ";
                }
                filter += string.Format("(BUGName like '%{0}%' or TSID like '%{0}%')", _keyTxt);
            }

            string _filter;
            if (!string.IsNullOrEmpty(filter))
            {
                _filter = "(" + filter + ")";
            }
            else
            {
                _filter = filter;
            }

            return _filter;
        }

        private string getFilter(string bug_status)
        {
            string filter = "";
            if (QDUserHelper.CurUser.IsManager)
            {
                switch (bug_status)
                {

                    case "tpNoSubmit": //未提交
                        {
                            filter = string.Format("Status='{0}'", TestStatus.noSubmit.ToString());
                            break;
                        }
                    //case "tpSubmit": //已提交
                    //    {
                    //        filter = string.Format("Status='{0}'", TestStatus.waitingProcess.ToString());
                    //        break;
                    //    }
                    case "tpWaitProcess": //待处理
                        {
                            filter = string.Format("Status='{0}'", TestStatus.waitingProcess.ToString());
                            break;
                        }
                    //case "tpProcessed": //已处理
                    //    {
                    //        filter = string.Format("Status='{0}'", TestStatus.waitingConfirm.ToString());
                    //        break;
                    //    }
                    case "tpConfirm": //待确认
                        {
                            filter = string.Format("Status='{0}'", TestStatus.waitingConfirm.ToString());
                            break;
                        }
                    case "tpFinish": //已完成
                        {
                            filter = string.Format("Status='{0}'", TestStatus.finish.ToString());
                            break;
                        }
                    case "tpRecall": //已撤消
                        {
                            filter = string.Format("Status='{0}'", TestStatus.recall.ToString());
                            break;
                        }
                }
            }
            else
            {
                switch (bug_status)
                {

                    case "tpNoSubmit": //未提交
                        {
                            filter = string.Format("CreatorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.noSubmit.ToString());
                            break;
                        }
                    //case "tpSubmit": //已提交
                    //    {
                    //        filter = string.Format("CreatorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingProcess.ToString());
                    //        break;
                    //    }
                    case "tpWaitProcess": //待处理
                        {
                            filter = string.Format("(CreatorCode='{0}' or NextProcessorCode='{0}') and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingProcess.ToString());
                            break;
                        }
                    //case "tpProcessed": //已处理
                    //    {
                    //        filter = string.Format("CreatorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingConfirm.ToString());
                    //        break;
                    //    }
                    case "tpConfirm": //待确认
                        {
                            filter = string.Format("(CreatorCode='{0}' or NextProcessorCode='{0}') and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.waitingConfirm.ToString());
                            break;
                        }
                    case "tpFinish": //已完成
                        {
                            filter = string.Format("CreatorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.finish.ToString());
                            break;
                        }
                    case "tpRecall": //已撤消
                        {
                            filter = string.Format("CreatorCode='{0}' and Status='{1}'", QDUserHelper.CurUser.Uid, TestStatus.recall.ToString());
                            break;
                        }
                }
            }

            return filter;
        }

        private void ts_Reload_Click(object sender, EventArgs e)
        {
            this.curPageIndex.Text = "1";
            DataBind();
        }

        void BaseForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            {
                ts_append_Click(sender, e);
            }
            else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
            {
                ts_delete_Click(sender, e);
            }
            else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.E)
            {
                ts_modify_Click(sender, e);
            }
            else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.S)
            {
                ts_Update_Click(sender, e);
            }
        }

        private void bugList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                string _tsId = this.bugList.Rows[e.RowIndex].Cells["listTSID"].Value.ToString();
                InitUIData(_tsId);

                var submit = this.SubmitToCode.SelectedValue.ToString();
                if (QDUserHelper.CurUser.Uid == submit /*&& _creatorCode!=submit*/ && _Status == "waitingProcess")
                {
                    this.btnDispose.Visible = true;
                    this.btnSubmit.Visible = false;
                    this.btnFinish.Visible = false;
                    this.btnreCall.Visible = false;
                    this.btnTransfer.Visible = false;
                    this.TransferMan.Visible = false;
                }
                else
                {
                    this.btnDispose.Visible = false;
                    this.btnSubmit.Visible = true;
                    this.btnFinish.Visible = true;
                    this.btnreCall.Visible = true;
                    this.btnTransfer.Visible = true;
                    this.TransferMan.Visible = true;
                }
            }
        }

        protected void InitUIData(string tsid)
        {
            try
            {
                PageState = PageState.Browse;
                this.SubmitToCode.Enabled = false;
                this.cmbQfCode.Enabled = false;

                QDResources db = new QDResources();
                Test_BUG mst = db.Test_BUG.FirstOrDefault(p => p.TSID == tsid);

                if (mst != null)
                {
                    this._TSID = tsid;
                    this.BUGName.Text = mst.BUGName;
                    if (!string.IsNullOrEmpty(mst.FilePath))
                    {
                        //System.IO.MemoryStream mstream = new System.IO.MemoryStream(mst.BUGContext, false);
                        //this.BUGContext.LoadFile(mstream, RichTextBoxStreamType.RichText);
                        //2021年4月20日09:17:01 修改  调用解压方法赋值

                        byte[] b = RtfHelper.DownloadFiles(mst.FilePath);
                        RtfHelper.LoadRichTextBoxData(this.BUGContext, b);
                    }
                    else
                    {
                        this.BUGContext.Clear();
                    }
                    _Status = mst.Status;
                    this.cmbQfCode.SelectedValue = mst.QfCode;
                    this.SubmitToCode.SelectedValue = mst.SubmitToCode;
                    this.lacreatorname.Text = mst.CreatorName;
                    this.lacreatedate.Text = mst.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                    BeginEdit(false);
                    Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                }
                else
                {
                    throw new Exception("BUG[" + this._TSID + "]不存在或已经被删除！");
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private Test_BUG IsCurrentExists(QDResources dbConfig)
        {
            Test_BUG mst = null;
            if (string.IsNullOrEmpty(this._TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                mst = dbConfig.Test_BUG.FirstOrDefault(p => p.TSID == _TSID);

                if (mst == null)
                {
                    PromptHelper.Prompt("BUG [" + this._TSID + "] 未保存或已经被删除！");
                }
            }

            return mst;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认提交当前BUG？") == DialogResult.OK)
                    {
                        if (!(mst.Status == TestStatus.noSubmit.ToString() || mst.Status == TestStatus.waitingConfirm.ToString()))
                        {
                            throw new Exception("当前BUG开发人员未处理，不可以提交！");
                        }
                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }

                        mst.LastProcessDate = DateTime.Now;
                        mst.NextProcessorCode = mst.SubmitToCode;
                        mst.NextProcessorName = mst.SubmitToName;
                        mst.Status = TestStatus.waitingProcess.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "提交", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("提交成功！");
                        Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认完成当前BUG？") == DialogResult.OK)
                    {
                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }
                        else if (!(mst.Status == TestStatus.waitingConfirm.ToString()))
                        {
                            throw new Exception("当前BUG开发人员未处理，不可以完成！");
                        }
                        mst.LastProcessDate = DateTime.Now;
                        mst.NextProcessorCode = "";
                        mst.NextProcessorName = "";
                        mst.Status = TestStatus.finish.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "完成", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("完成成功！");
                        Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void btnreCall_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认撤消当前BUG？") == DialogResult.OK)
                    {
                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }

                        mst.LastProcessDate = DateTime.Now;
                        mst.NextProcessorCode = "";
                        mst.NextProcessorName = "";
                        mst.Status = TestStatus.recall.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "撤消", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("撤消成功！");
                        Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认转移当前BUG？") == DialogResult.OK)
                    {
                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }
                        //else if (!(mst.Status == TestStatus.waitingConfirm.ToString()))
                        //{
                        //    throw new Exception("当前BUG开发人员未处理，不可以转移");
                        //}

                        if (this.TransferMan.SelectedIndex == -1)
                        {
                            throw new Exception("请选择转移接收人！");
                        }

                        mst.LastProcessDate = DateTime.Now;
                        mst.SubmitToCode = this.TransferMan.SelectedValue.ToString();
                        mst.SubmitToName = this.TransferMan.Text;
                        mst.NextProcessorCode = this.TransferMan.SelectedValue.ToString();
                        mst.NextProcessorName = this.TransferMan.Text;
                        mst.Status = TestStatus.waitingProcess.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "转移", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("转移成功！");
                        Test_BUGHelper.BindProcessList(this.listLog, this._TSID);
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void curPageIndex_TextChanged(object sender, EventArgs e)
        {
            DataBind();
        }

        private void t_monitoring_Tick(object sender, EventArgs e)
        {
            this.curPageIndex.Text = "1";
            DataBind();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            DataBind();
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        private void ts_next_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                QDResources db = new QDResources();
                string filter = getFilter();
                string sql = string.Format("select top 1 TSID from Test_BUG where QfCode='{2}' and TSID>'{0}' and {1} order by TSID asc", _TSID, filter, _QfCode);
                object _tsId = db.ExecuteScalar(sql);
                if (_tsId == null || _tsId.ToString().Length == 0)
                {
                    PromptHelper.Prompt("已经是最后一条数据了！");
                }
                else
                {
                    InitUIData(_tsId.ToString());
                }
            }
        }

        private void ts_prev_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_TSID))
            {
                PromptHelper.Prompt("未加载任何BUG信息！");
            }
            else
            {
                QDResources db = new QDResources();
                string filter = getFilter();
                string sql = string.Format("select top 1 TSID from Test_BUG where QfCode='{2}' and TSID<'{0}' and {1} order by TSID desc", _TSID, filter, _QfCode);
                object _tsId = db.ExecuteScalar(sql);
                if (_tsId == null || _tsId.ToString().Length == 0)
                {
                    PromptHelper.Prompt("已经是第一条数据了！");
                }
                else
                {
                    InitUIData(_tsId.ToString());
                }
            }
        }

        private void gridList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (this.gridList.Rows.Count > 0)
                {
                    _QfCode = this.gridList.Rows[e.RowIndex].Cells["QfCode"].Value.ToString();
                    _DeveloperCode = this.gridList.Rows[e.RowIndex].Cells["DeveloperCode"].Value.ToString();
                    _LeaderCode = this.gridList.Rows[e.RowIndex].Cells["LeaderCode"].Value.ToString();
                    addClick();
                    DataBind();
                }
            }
        }
        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.gridList.CopyFirstSelectedCellValue();
        }

        private void 复制所有选中单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.gridList.CopySelectedCellsValue();
        }
        Form nf;
        TextBox tb;
        string _strPath = "";
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            QDResources db = new QDResources();
            var path = db.ExecuteScalar("select BTFilePath from Sys_Setting");
            if (path != null)
            {
                _strPath = path.ToString();
            }
            nf = new Form();
            int _w = 410;
            int _h = 150;
            nf.Width = _w;
            nf.Height = _h;
            //添加textbox
            tb = new TextBox();
            tb.Name = "txt";
            //tb.Multiline = true;
            tb.Top = 50;
            tb.Left = 5;
            tb.Width = 300;
            tb.Text = _strPath;
            nf.Controls.Add(tb);
            //添加保存按钮
            Button but = new Button();
            but.Top = 50;
            but.Left = 310;
            but.Name = "btnSave";
            but.Text = "保存";
            but.Click += But_Click;
            nf.Controls.Add(but);
            nf.StartPosition = FormStartPosition.CenterScreen;
            nf.MaximizeBox = false;
            nf.MinimizeBox = false;
            nf.ShowIcon = false;
            nf.Text = "保存路径";
            nf.ShowDialog();

        }

        private void But_Click(object sender, EventArgs e)
        {
            var path = tb.Text;
            if (_strPath == "")
            {
                QDResources db = new QDResources();
                db.ExecuteNonQuery(string.Format("insert into Sys_Setting (BTFilePath) VALUES ('{0}')", path));
            }
            else
            {
                QDResources db = new QDResources();
                db.ExecuteNonQuery(string.Format("UPDATE Sys_Setting SET BTFilePath = '{0}'", path));
            }
            MessageBox.Show("保存成功！");
            nf.Close();
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDispose_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState != PageState.Browse)
                {
                    throw new Exception("当前BUG未保存！");
                }
                QDResources dbConfig = new QDResources();
                Test_BUG mst = IsCurrentExists(dbConfig);
                if (mst != null)
                {
                    if (PromptHelper.PromptOkCancel("确认处理当前BUG？") == DialogResult.OK)
                    {

                        if (mst.Status == TestStatus.finish.ToString())
                        {
                            throw new Exception("当前BUG已完成！");
                        }
                        else if (mst.Status == TestStatus.recall.ToString())
                        {
                            throw new Exception("当前BUG已撤消！");
                        }
                        else if (mst.Status != TestStatus.waitingProcess.ToString())
                        {
                            throw new Exception("当前BUG测试未提交，不可以处理！");
                        }
                        else if (mst.NextProcessorCode != QDUserHelper.CurUser.Uid)
                        {
                            throw new Exception("当前BUG的处理人为[" + mst.NextProcessorName + "]！");
                        }

                        mst.LastProcessDate = DateTime.Now;
                        mst.NextProcessorCode = mst.CreatorCode;
                        mst.NextProcessorName = mst.CreatorName;
                        mst.Status = TestStatus.waitingConfirm.ToString();

                        Test_BUGHelper.AddBugProcessList(dbConfig, this._TSID, QDUserHelper.CurUser.Uid, QDUserHelper.CurUser.UName, this.ProcessDesc.Text.Trim(), "处理", mst.NextProcessorCode, mst.NextProcessorName);
                        dbConfig.SaveChanges();
                        PromptHelper.Prompt("提交成功！");
                        //this.ProcessDesc.Clear();
                        //Test_BUGHelper.BindProcessList(this.listLog, this._TSID);


                        //this.btnDispose.Visible = false;
                        //this.btnSubmit.Visible = true;
                        //this.btnFinish.Visible = true;
                        //this.btnreCall.Visible = true;
                        //this.btnTransfer.Visible = true;
                        //this.TransferMan.Visible = true;

                        DataBind();
                        addClick();
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        //private void gridList_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        //{
        //    e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        //}
    }
}
